<!--
*@Author: zt
*@Description: 添加值班人员
*@Date: 2024-08-27
-->
<template>
  <u-dialog
    v-bind="$attrs"
    :confirmLoading="loading"
    @submit="submit"
    @close="dialogClose"
    :hideBtns="attrs.dbDisabled ? ['submit'] : []"
  >
    <a-layout class="f-h-100 s-bg-white">
      <a-layout-content style="overflow: hidden">
        <a-row :gutter="30" class="f-h-100">
          <a-col :span="12">
            <u-busi-card title="基本信息">
              <u-form
                :elements="formEls"
                :model="form"
                :loading="loading"
                :gutter="0"
                ref="formRef"
                @formChange="formChange"
              ></u-form>
            </u-busi-card>
            <u-busi-card title="成员信息">
              <a-list
                :grid="{ gutter: [16, 16], column: 4 }"
                style="margin-left: 8px"
                :data-source="userList"
              >
                <template #renderItem="{ item }">
                  <a-row align="middle">
                    <div class="u-name-box">{{ item.name }}</div>
                    <a-space
                      direction="vertical"
                      align="middle"
                      class="f-margin-l10"
                    >
                      <span class="u-span-name f-font-family">
                        {{ item.name }}
                      </span>
                      <span class="u-span-value f-font-family">
                        当月值班天数
                        <span style="color: #333">
                          {{ item.standsDays }}
                        </span>
                      </span>
                    </a-space>
                  </a-row>
                </template>
              </a-list>
            </u-busi-card>
          </a-col>
          <a-col :span="12" class="f-h-100">
            <div class="f-flex-column f-h-100">
              <Calendar
                :showExtraTool="false"
                v-model:date="clickDateValue"
                :data="calendarData"
                @search="getCalendarData()"
                @item-click="
                  data => {
                    userListRow(data.standbyDate);
                  }
                "
              ></Calendar>
            </div>
          </a-col>
        </a-row>
      </a-layout-content>
    </a-layout>
    <userRow
      v-model:open="showUserRow"
      width="80%"
      :data="useListData"
      title="当日值班人员"
    />
  </u-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, useAttrs } from 'vue';
import { useBaseStore } from '@/store';
import { storeToRefs } from 'pinia';
import { alertC, messageC, nullC, isValue } from '@/util/common';
import { cloneDeep } from 'lodash';
import dayjs, { Dayjs } from 'dayjs';
import Calendar from '@/views/oa/assist/myCalender/Calender.vue';
import userRow from '@/views/oa/administration/beDuty/row.vue';
import * as beDutyApi from '@/service/administration/beDuty/index';

const props = defineProps<{
  calenderValue?: string
}>()

const attrs = useAttrs();
const emits = defineEmits(['success', 'close']);

const { deptData, deptUsers } = storeToRefs(useBaseStore());
let showUserRow = ref(false);
let useListData = ref([]);
const formRef = ref<FormInstance>();
const form = reactive<any>({
  fkdeptname: '',
  standbyDate: '',
  backuptype: 2,
  appendixSaveVOList: [],
});
const formItemProps: FormItemProps & _IExtra = {
  labelWidth: '90px',
  colon: false,
};
let depUserOptions = computed(() => {
  let deptUserss = deptUsers.value.find(i => i.keyid == form.fkdeptid);
  return deptUserss ? (deptUserss['children'] || []) : [];
});
let userList = ref([]);

let formWorkDataMonth = ref<string>('');

let formEls: Array<_IFormEl> = reactive([
  {
    label: '值班时间',
    key: 'standbyDate',
    col: { span: 24 },
    element: 'datepicker',
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      allowClear: false,
      onChange: function (val) {
        clickDateValue.value = val;
        getCalendarData(val);
      },
    },
  },
  {
    label: '值班部门',
    key: 'fkdeptid',
    col: { span: 24 },
    element: 'select',
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      options: deptData.value,
      fieldNames: { label: 'name', value: 'keyid' },
      onChange: function (val, val1) {
        form.fkdeptname = val1.name;
        form.fkleaderid = '';
        form.fkuserids = '';
      },
    },
  },
  {
    label: '值班领导',
    key: 'fkleaderid',
    col: { span: 24 },
    element: 'select',
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      options: depUserOptions,
      fieldNames: { label: 'name', value: 'keyid' },
      onChange: function (val, val1) {
        getUserList();
      },
    },
  },
  {
    label: '值班人员',
    key: 'fkuserids',
    col: { span: 24 },
    element: 'select',
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      options: depUserOptions,
      fieldNames: { label: 'name', value: 'keyid' },
      mode: 'multiple',
      onChange: function (val, val1) {
        getUserList();
      },
    },
  },
  {
    label: '备注',
    key: 'reason',
    col: { span: 24 },
    element: 'textarea',
    formItemProps: { ...formItemProps },
  },
  {
    label: '附件',
    key: 'appendixSaveVOList',
    col: { span: 24 },
    element: 'file',
    formItemProps: { ...formItemProps },
    componentProps: {
      fileParams: { biztype: '5', bucket: 'ADM' },
    },
  },
]);

// 保存提交
const loading = ref<boolean>(false)
const submit = async () => {
  loading.value = true;
  try {
    await formRef.value.form.validate()

    if (verifyUser() == false) {
      loading.value = false;
      return;
    }
  
    let tFrom = cloneDeep(form);
  
    tFrom.fkleaderid = tFrom.fkleaderid;
    tFrom.backuptype = 2;
    const result = await beDutyApi.add(tFrom);
    if (result.code == 0) {
      emits('success', form.standbyDate);
      messageC(result.msg, 'success');
      dialogClose();
    } else {
      alertC(result.msg, 'warning');
    }
  } catch (error) {}
  loading.value = false;

};

// 验证值班人员是否在当天已经值过班了
const verifyUser = (): boolean => {
  let montDatas = currentMonthWordData.value[dayjs(form.standbyDate).format('YYYY-MM')] || []
  let users = montDatas.filter(
    i =>
      dayjs(i.standbyDate).format('YYYY-MM-DD') ==
      dayjs(form.standbyDate).format('YYYY-MM-DD')
  );
  let exitUsers = users.filter(i =>
    (form['fkuserids'] || []).includes(i.fkuserid)
  );
  if (exitUsers.length != 0) {
    let userNames = exitUsers.map(i => nullC(i.fkusername)).join('/');
    messageC(`已存在${form.standbyDate}${userNames}的值班数据！`);
    return false;
  }
  return true;
};

const dialogClose = () => {
  form.standbyDate = dayjs(new Date()).format('YYYY-MM-DD');
  userList.value = [];
  form.fkdeptid = '';
  form.appendixSaveVOList = [];
  form.fkuserids = '';
  form.standbyDate = '';
  form.reason = '';
  formRef.value.form.resetFields();
  emits('close');
};

// 日历数据
const clickDateValue = ref<Dayjs>(dayjs().format('YYYY-MM-DD'));
const currentMonthWordData = ref<object>({}); // 月值班的所有数据
const calendarData = ref<any[]>([]);
const getCalendarData = async () => {
  try {
    const res = await beDutyApi.dutyUserPage({
      datetime: clickDateValue.value,
      backuptype: 2,
    });
    if (res.code == 0) {
      let tData = res.data || [];

      // 月值班数据
      currentMonthWordData.value[dayjs(clickDateValue.value).format('YYYY-MM')] = tData;
    
      let count = {};
      tData.forEach(item => {
        count[item.standbyDate] = (count[item.standbyDate] || 0) + 1;
        if (count[item.standbyDate] < 4) {
          item.scheduledate = dayjs(item.standbyDate).format(
            'YYYY-MM-DD HH:mm:ss'
          );
          item.theme = item.fkusername || '';
        } else if (count[item.standbyDate] == 4) {
          item.scheduledate = dayjs(item.standbyDate).format(
            'YYYY-MM-DD HH:mm:ss'
          );
          item.theme = '...';
        }
      });
      tData = tData.filter(i => isValue(i.theme));
      calendarData.value = tData;
    }
  } catch (error) {}
};

// 查询视图数据
const userListRow = async date => {
  try {
    const res = await beDutyApi.dutyUserPage({
      datetime: clickDateValue.value,
      backuptype: 2,
    });

    if (res.code == 0) {
      let tData = res.data || [];

      tData.forEach(item => {
        (item.scheduledate = dayjs(item.standbyDate).format(
          'YYYY-MM-DD HH:mm:ss'
        )),
          (item.theme = item.fkusername || '');
      });
      useListData.value = [];
      tData.forEach(item => {
        if (item.scheduledate == date) {
          useListData.value.push(item);
        }
      });
      showUserRow.value = true;
    }
  } catch (error) {}
};

//获取回显数据
const getHX = async () => {
  loading.value = true;
  try {
    const res = await beDutyApi.getQuery(attrs.keyid);
    if (res.code == 0) {
      for (let key in res.data) {
        if (key == 'appendix') {
          form['appendixSaveVOList'] = res.data[key] || [];
        } else {
          form[key] = res.data[key];
        }
      }
      form['fkuserids'] = form['fkuserid'];
      getUserList();
    }
  } catch (error) {}
  loading.value = false;
};

// 成员信息列表
const getUserList = () => {
  let userIds = (form['fkuserids'] || '').split(',').filter(i => isValue(i));
  if (form.fkleaderid) {
    userIds.push(form.fkleaderid);
  }
  userIds = Array.from(new Set(userIds));

  userList.value = depUserOptions.value.filter(i => userIds.includes(i.keyid));

  getDutyUserDay();
};

// 获取备勤人员展示天数
const getDutyUserDay = async () => {
  let montDatas = currentMonthWordData.value[dayjs(form.standbyDate).format('YYYY-MM')] || []
  userList.value.forEach(i => {
    let resuls = montDatas.filter(o => o.fkuserid == i.keyid);
    i.standsDays = resuls.length;
  });
};

watch(
  () => attrs.open,
  async (nva, oval) => {
    if (attrs.open == true) {
      clickDateValue.value = dayjs(props.calenderValue || new Date()).format('YYYY-MM-DD'),
      form.standbyDate = dayjs(props.calenderValue || new Date()).format('YYYY-MM-DD'),
      await getCalendarData();
      if (attrs.keyid != '') {
        await getHX();
        getUserList();
      } else {
        for (let key in form) {
          if (key != 'standbyDate') {
            form[key] = '';
            form['fkuserids'] = '';
            form['appendixSaveVOList'] = [];
            form['keyid'] = '';
            form['backuptype'] = 2;
          }
        }
      }
    }
  }
);
</script>

<style lang="scss" scoped>
.u-name-box {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  text-align: center;
  line-height: 80px;
  background: linear-gradient(348deg, #1890ff 0%, #dbedfe 100%);
  font-size: var(--font-size-level-1);
  color: #fff;
}

.u-span-name {
  font-weight: 400;
  font-size: var(--font-size-level-2);
  color: #1890ff;
}

.u-span-value {
  font-weight: 400;
  font-size: var(--font-size-level-1);
  color: #666666;
}
</style>
